import React, { useState, useEffect } from 'react'
import { Space, Table, Tag, Pagination, Card, Switch, Button, message, Drawer, Form, Input, Radio, Modal, TreeSelect, Upload } from 'antd'
import { SearchOutlined, EditOutlined, CloseOutlined, PlusOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import api from '@/api'
const { Search } = Input;

export default function () {
    let timeout: ReturnType<typeof setTimeout> | null;
    let currentValue: string;
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [img, setImg] = useState([]);
    const [List, setLsit] = useState()
    const [sendList, setSendList] = useState({
        pageSize: 5,
        currentPage: 1,
        type: null
    })
    const [open, setOpen] = useState(false);
    const [isadd, setisadd] = useState(false);
    const [form] = Form.useForm();
    const [write, setwrite] = useState(false);
    const [data, setdata] = useState({
        name: '',
        detail: '',
        price: '',
        state: '',
        type: '',
        stock: '',
        id: null
    })
    const [total, setTotal] = useState()
    const [typeList, setTypeList] = useState([])
    let imgs = ''

    const adduser = () => {
        setisadd(true)
        form.setFieldsValue({
            name: '',
            detail: '',
            price: '',
            state: '',
            type: '',
            stock: '',
            id: null
        });
        setOpen(true);
    }
    async function setDetail(args: any) {
        console.log(args);

        const res = await api.good.searchOneGoods({ id: args })
        setwrite(true)
        setOpen(true);
        console.log(res.data.data);
        const data = res.data.data
        form.setFieldsValue({
            name: data.info[0].name,
            detail: data.info[0].detail,
            price: data.info[0].price,
            state: data.info[0].state,
            type: data.info[0].type,
            stock: data.info[0].stock,
            id: data.info[0].id
        });


    }
    async function getDetail(args: any) {
        setIsModalOpen(true);
        const res = await api.good.getGoodsImg({ id: args })
        console.log("商品图片", res);
        setImg(res.data.data)

    }
    async function getList(params: any) {
        const res = await api.good.getNomarlGoodsList(params)
        console.log('normalgoodsList', res.data.total);
        setTotal(res.data.total)
        setLsit(res.data.data)

    }
    async function changeGoodsState(args: string, id: number) {
        console.log(args, id);

        const res = await api.good.updateGoods({ id, state: args })

        message.success(res.data.msg)
        getList(sendList)

    }
    async function getGoodsType() {
        const res = await api.good.getGoodsType()
        console.log(res.data.arr);
        let oldlist = res.data.arr

        // console.log('ffff', change(oldlist));
        let newss = change(oldlist)
        setTypeList(newss)

        function change(args: any) {
            let newlist: any = []
            args.forEach((item: any) => {
                let obj: any = {}
                obj['title'] = item.i
                obj['value'] = item.id
                if (item.child && item.child.length > 0) {
                    obj.children = change(item.child)
                }
                newlist.push(obj)
                return newlist
            })
            return newlist
        }




    }
    useEffect(() => {
        getList(sendList)
        getGoodsType()
    }, [])

    const handleCancel = () => {
        setIsModalOpen(false);
    };
    const columns: ColumnsType<any> = [

        {
            title: 'id',
            dataIndex: 'id',
            key: 'id',
        },

        {
            title: '名称',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '介绍',
            dataIndex: 'detail',
            key: 'detail',
        },
        {
            title: '价格',
            dataIndex: 'price',
            key: 'price',
        },
        // {
        //     title: '商品图片',
        //     dataIndex: 'img',
        //     key: 'img',
        //     render: (_, item) => (
        //         <img src={item.img} style={{ width: '50px', height: '50px' }}></img>
        //     ),

        // },
        {
            title: '库存',
            dataIndex: 'stock',
            key: 'stock',
        },
        {
            title: '热度',
            dataIndex: 'hot',
            key: 'hot',
        },

        {
            title: '是否下架',
            dataIndex: 'state',
            key: 'state',
            render: (_, item) => {
                console.log('item', item.state);

                if (item.state == 1) {
                    return (
                        <Space direction="vertical">
                            <Switch checkedChildren="未下架" unCheckedChildren="已下架" onChange={() => { changeGoodsState('0', item.id) }} defaultChecked={true} />
                        </Space>
                    )
                } else {
                    return (
                        <Space direction="vertical">
                            <Switch checkedChildren="未下架" unCheckedChildren="已下架" onChange={() => { changeGoodsState('1', item.id) }} defaultChecked={false} />
                        </Space>
                    )
                }

            },
        },
        {
            title: '操作',

            render: (_, record) => (
                <Space size="middle">
                    <Button type="primary" ghost shape="circle" icon={<EditOutlined />} onClick={() => setDetail(record.id)}> </Button>
                    <Button type="primary" ghost shape="circle" icon={<SearchOutlined />} onClick={() => getDetail(record.id)}> </Button>
                    <Button type="primary" danger shape="circle" icon={<CloseOutlined />} onClick={() => del(record.id)}></Button>

                </Space >
            ),
        },




    ]
    const onClose = () => {
        setOpen(false);
    };
    async function submit(arg: any) {
        if (isadd) {
            console.log('ggggg', imgs);
            const res = await api.good.addGoods({ ...arg, img: imgs })
            message.success(res.data.msg)
            getList(sendList)

        } else {
            const res = await api.good.updateGoods({ ...arg, img: imgs })
            message.success(res.data.msg)
            getList(sendList)

        }

    }
    function filechange(args: any) {
        if (args.file.status == 'done') {
            console.log(args.file.response.url);
            imgs = args.file.response.url
        }
    }
    async function del(args: any) {
        const res = await api.good.delGoods({ id: args })

        message.success(res.data.msg)
        getList(sendList)
    }
    function pageChange(args: any) {

        console.log(args);
        getList({ ...sendList, currentPage: args })
        setSendList({ ...sendList, currentPage: args })

    }
    const onSearch = async (value: string) => {
        console.log('search:', value);
        const res = await api.good.SearchGoods({ pageSize: 10, currentPage: 1, querystr: value })
        console.log("res", res.data.data);
        setLsit(res.data.data)

    };
    const reset = () => {
        getList(sendList)
    }
    return (
        <div>
            <Card>
                <div style={{ display: "flex", justifyContent: "space-between" }}>
                    <div>
                        <Search
                            placeholder="input search text"
                            allowClear
                            enterButton="Search"
                            style={{ width: 500 }}
                            size="large"
                            onSearch={onSearch}
                        />
                        <Button type="primary" onClick={reset} size='large'>重置</Button>
                    </div>

                    <div>
                        <Button type="primary" danger onClick={adduser} >+</Button>
                    </div>
                </div>


                <Table columns={columns} dataSource={List} pagination={false} />
                <Drawer title="用户" placement="right" onClose={onClose} open={open}>
                    <Form
                        labelCol={{ span: 4 }}
                        wrapperCol={{ span: 14 }}
                        layout="horizontal"
                        style={{ maxWidth: 600 }}
                        onFinish={submit}
                        form={form}
                    >
                        {
                            !isadd ? <Form.Item label="编号:" name='id'>
                                <Input disabled={true} />
                            </Form.Item> : <></>
                        }
                        <Form.Item label="商品名:" name='name' >
                            <Input />
                        </Form.Item>

                        <Form.Item label="商品介绍:" name='detail'>
                            <Input value={data.name} />
                        </Form.Item>
                        <Form.Item label="商品库存:" name='stock'>
                            <Input value={data.stock} />
                        </Form.Item>
                        <Form.Item label="商品图片：" valuePropName="fileList" >
                            <Upload action="http://localhost:3005/api/upload" listType="picture-card" maxCount={1} name='file' onChange={filechange} >
                                <div>
                                    <PlusOutlined />
                                    <div style={{ marginTop: 8 }}>Upload</div>
                                </div>
                            </Upload>
                        </Form.Item>

                        <Form.Item label="商品状态:" name='state'>
                            <Radio.Group value={data.state}>
                                <Radio value="0"> 未上架 </Radio>
                                <Radio value="1"> 已上架 </Radio>
                            </Radio.Group>
                        </Form.Item>
                        <Form.Item label="价格:" name='price'>
                            <Input value={data.price} />
                        </Form.Item>

                        <Form.Item label="选择商品类型:" name='type'>
                            <TreeSelect
                                treeData={typeList}
                            />
                        </Form.Item>

                        {isadd ? <Form.Item >
                            <Button htmlType='submit'>添加</Button>
                        </Form.Item> : <Form.Item >
                            {
                                write ? <Button htmlType='submit'>修改</Button> : <Button onClick={() => { setOpen(false) }}>确定</Button>
                            }
                        </Form.Item>}


                    </Form>
                </Drawer>
                <Modal title="商品图片" open={isModalOpen} onCancel={handleCancel} footer={false}>
                    {
                        img.map((item: any) =>
                            <img src={item.img} style={{ width: '100px', height: '100px', margin: "10px" }}></img>)
                    }
                </Modal>
                <Pagination total={total} current={sendList.currentPage} pageSize={sendList.pageSize} onChange={pageChange}></Pagination>
            </Card>
        </div>
    )
}
